/**
 * @description 
 * @author cq
 * @Date 2021-04-06 16:07:02
 * @LastEditTime 2021-04-07 15:45:59
 * @LastEditors cq
 */


// reducer 就是我们传入的reducer
// enhancer 就是applyMiddleware的返回值
export default function createStore(reducer, enhancer) {

  // 就去加强我们的dispatch
  if (enhancer) {
    return enhancer(createStore)(reducer)
  }

  let curState;
  let curListen = []


  function getState(params) {
    return curState
  }

  function dispatch(action) {
    curState = reducer(curState, action)
    curListen.forEach(item => item())

  }

  function subscribe(listen) {
    curListen.push(listen);
    // 取消订阅
    return () => {
      const index = curListen.findIndex(el => el === listen)
      curListen.splice(index, 1)
    }
  }

  // 手动触发一次dispatch派发初始值

  dispatch({
    type: "随机字符串"
  })

  return {
    getState,
    dispatch,
    subscribe
  }
}
